/*
 * @Author       : zu1662
 * @Date         : 2020-12-01 15:42:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-10 14:56:31
 * @Description  : 文件下载
 */
// 下载插件
import { service } from '@/utils/request'

function downloadFn (url, params, type) {
  // const temp = Intl.DateTimeFormat().resolvedOptions().timeZone
  // params.timezone = temp
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: type || 'post',
      data: params,
      responseType: 'blob'
    })
      .then(res => {
        const fileName = decodeURI(res.headers['content-disposition'].split('=')[1])
        const content = res.data
        const blob = new Blob([content])
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName.slice(7)
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        resolve('success')
      })
      .catch(err => {
        reject(err)
      })
  })
}

const DownloadPlugin = {}
DownloadPlugin.install = (Vue) => {
  Vue.prototype.$download = downloadFn
}

export default DownloadPlugin
